package com.show.business.device.service.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.show.business.common.core.domain.AjaxResult;
import com.show.business.common.utils.DateUtils;
import com.show.business.common.utils.StringUtils;
import com.show.business.device.bean.*;
import com.show.business.device.bean.vo.AlarmTmpVo;
import com.show.business.device.mapper.DeviceAlarmMapper;
import com.show.business.device.mapper.DeviceGroupAlarmPhoneMapper;
import com.show.business.device.service.*;
import com.show.business.integrate.bean.DyvmConfig;
import com.show.business.integrate.bean.DyvmMessage;
import com.show.business.integrate.bean.SmsConfig;
import com.show.business.integrate.bean.SmsMessage;
import com.show.business.integrate.service.IDyvmConfigService;
import com.show.business.integrate.service.IDyvmMessageService;
import com.show.business.integrate.service.ISmsConfigService;
import com.show.business.integrate.service.ISmsMessageService;
import com.show.dyvm.AliDyvmUtil;
import com.show.sms.AliSmsUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * <p>
 * 设备告警 服务实现类
 * </p>
 *
 * @author dvlp
 * @since 2024-09-30
 */
@Service
public class DeviceAlarmServiceImpl extends ServiceImpl<DeviceAlarmMapper, DeviceAlarm> implements IDeviceAlarmService {
    private static  SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
    @Resource
    private IDeviceManageService deviceManageService;

    @Resource
    private IDeviceGroupService deviceGroupService;

    @Resource
    private DeviceGroupAlarmPhoneMapper deviceGroupAlarmPhoneMapper;

    @Resource
    private ISmsConfigService smsConfigService;

    @Resource
    private IDyvmConfigService dyvmConfigService;

    @Resource
    private ISmsMessageService smsMessageService;

    @Resource
    private IDyvmMessageService dyvmMessageService;


    @Override
    public List<DeviceAlarm> getList(DeviceAlarm deviceAlarm) {
        return baseMapper.getList(deviceAlarm);
    }

    /**
     * 告警信息存储
     * If type <=4:(1:通电、0:断电/缺相);If type==5:(1:通电、0:断线)）；State=0时，检测220V为断电，检测380V为缺相"
     * @param uartTmp
     * @return
     */
    @Override
    @Transactional
    public AjaxResult saveInfo(UartTmp uartTmp) {System.out.println("WWWWWWWWWWWWWWWW---:"+uartTmp.getImei());
        DeviceManage deviceManage=deviceManageService.getDeviceByImei(uartTmp.getImei());
        //判断设备是否存在
        if(ObjectUtil.isNotEmpty(deviceManage)){
            //判断设备类型单路还是多路
            if(deviceManage.getDeviceType().equals("0")){//单路
                //告警类型（0-断电；1-缺相；2:通电;3-通电；4-断线)
                if(ObjectUtil.isNotEmpty(uartTmp.getType()) && ObjectUtil.isNotEmpty(uartTmp.getState()) ){
                    //主线（type==0）(state==0,断电；state==1,通电)
                    if(uartTmp.getType().equals("0")){
                        //判断是否开启主线（告警类型（0-断电；1-缺相；2-通电恢复;3-设备断线；4-设备在线)）
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorMainline()) && deviceManage.getMonitorMainline().equals("0")){
                            if(uartTmp.getState().equals("0")){//断电-修改主设备断电
                                //处理设备告警信息-断电
                                this.saveAlarm(uartTmp,deviceManage,"0");
                                //断电处理设备相关状态()
                                deviceManage.setMainStrandState("0");//断电
                                if(deviceManage.getDeviceStatus().equals("0")){
                                    deviceManage.setDeviceStatus("1");//通电
                                }
                                deviceManageService.updateById(deviceManage);
                            }else if(uartTmp.getState().equals("1")){//通电-修改主设备通电
                                //处理设备告警信息-通电
                                this.saveAlarm(uartTmp,deviceManage,"2");
                                //处理设备信息
                                deviceManage.setMainStrandState("1");//通电
                                if(deviceManage.getDeviceStatus().equals("0")){
                                    deviceManage.setDeviceStatus("1");//通电
                                }
                                deviceManageService.updateById(deviceManage);
                            }
                        }
                    }else if(uartTmp.getType().equals("5")){//5-设备通信状态号子线(type==5)(1:通电、0:断线)
                        if(uartTmp.getState().equals("1")){//通电
                            if(!uartTmp.getState().equals(deviceManage.getDeviceStatus())){
                                this.saveAlarm(uartTmp,deviceManage,"4");//存储告警信息

                            }
                        }
                        if(deviceManage.getDeviceStatus().equals("0")){
                            deviceManage.setDeviceStatus("1");//通电
                        }
                        deviceManageService.updateById(deviceManage);
                    }
                }
            }else{//多路
                //告警类型（0-断电；1-缺相；2:通电;3-通电；4-断线)
                if(ObjectUtil.isNotEmpty(uartTmp.getType()) && ObjectUtil.isNotEmpty(uartTmp.getState()) ){
                    //主线（type==0）(state==0,断电；state==1,通电)
                    if(uartTmp.getType().equals("0")){
                        //判断是否开启主线（告警类型（0-断电；1-缺相；2-通电恢复;3-设备断线；4-设备在线)）
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorMainline()) && deviceManage.getMonitorMainline().equals("0")){
                            if(uartTmp.getState().equals("0")){//断电-修改主设备断电
                                //处理设备告警信息-断电
                                this.saveAlarm(uartTmp,deviceManage,"0");
                                //断电处理设备相关状态()
                                deviceManage.setMainStrandState("0");//断电
                                //判断是否开启1号子线
                                if(deviceManage.getMonitorOneStrand().equals("0")){
                                    deviceManage.setOneStrandState("0");//断电/缺相
                                }
                                //判断是否开启2号子线-检测220V为断电，检测380V为缺相(0-断电/缺相；1-通电)
                                if(deviceManage.getMonitorTwoStrand().equals("0")){
                                    deviceManage.setTwoStrandState("0");//断电/缺相
                                }
                                //判断是否开启3号子线--检测220V为断电，检测380V为缺相(0-断电/缺相；1-通电)
                                if(deviceManage.getMonitorThreeStrand().equals("0")){
                                    deviceManage.setThreeStrandState("0");//断电/缺相
                                }
                                //判断是否开启4号子线--检测220V为断电，检测380V为缺相(0-断电/缺相；1-通电)
                                if(deviceManage.getMonitorFourStrand().equals("0")){
                                    deviceManage.setFourStrandState("0");//断电/缺相
                                }
                                if(deviceManage.getDeviceStatus().equals("0")){
                                    deviceManage.setDeviceStatus("1");//通电
                                }
                                deviceManageService.updateById(deviceManage);
                            }else if(uartTmp.getState().equals("1")){//通电-修改主设备通电
                                //处理设备告警信息-通电
                                this.saveAlarm(uartTmp,deviceManage,"2");
                                //处理设备信息
                                deviceManage.setMainStrandState("1");//通电
                                if(deviceManage.getDeviceStatus().equals("0")){
                                    deviceManage.setDeviceStatus("1");//通电
                                }
                                deviceManageService.updateById(deviceManage);
                            }
                        }
                    }else if(uartTmp.getType().equals("1")){//1号子线(type==1)(state==1通电；断电：state==0且电压==200V；缺相：state==0且电压==380V；)
                        //判断是否开启1号子线
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorOneStrand()) && deviceManage.getMonitorOneStrand().equals("0")){
                            //判断告警状态（0-断电/缺相；1-通电；）
                            if(uartTmp.getState().equals("0")){//断电/缺相
                                this.saveAlarm(uartTmp,deviceManage,"0");//存储告警信息
                                deviceManage.setOneStrandState("0");//断电/缺相
                            }else if(uartTmp.getState().equals("1")){//通电
                                this.saveAlarm(uartTmp,deviceManage,"2");//存储告警信息
                                deviceManage.setOneStrandState("1");//通电
                            }
                            if(deviceManage.getDeviceStatus().equals("0")){
                                deviceManage.setDeviceStatus("1");//通电
                            }
                            deviceManageService.updateById(deviceManage);
                        }

                    }else if(uartTmp.getType().equals("2")){//2号子线(type==2)(state==1通电；断电：state==0且电压==200V；缺相：state==0且电压==380V；)
                        //判断是否开启2号子线
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorTwoStrand()) && deviceManage.getMonitorTwoStrand().equals("0")){
                            //判断告警状态（0-断电/缺相；1-通电；）
                            if(uartTmp.getState().equals("0")){//断电/缺相
                                this.saveAlarm(uartTmp,deviceManage,"0");// //存储告警信息
                                deviceManage.setTwoStrandState("0");//断电/缺相
                            }else if(uartTmp.getState().equals("1")){//通电
                                this.saveAlarm(uartTmp,deviceManage,"2");//存储告警信息
                                deviceManage.setTwoStrandState("1");//通电
                            }
                            if(deviceManage.getDeviceStatus().equals("0")){
                                deviceManage.setDeviceStatus("1");//通电
                            }
                            deviceManageService.updateById(deviceManage);
                        }
                    }else if(uartTmp.getType().equals("3")){//3号子线(type==3)(state==1通电；断电：state==0且电压==200V；缺相：state==0且电压==380V；)
                        //判断是否开启3号子线
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorThreeStrand()) && deviceManage.getMonitorThreeStrand().equals("0")){
                            //判断告警状态（0-断电/缺相；1-通电；）
                            if(uartTmp.getState().equals("0")){//断电/缺相
                                this.saveAlarm(uartTmp,deviceManage,"0");// //存储告警信息
                                deviceManage.setThreeStrandState("0");//断电/缺相
                            }else if(uartTmp.getState().equals("1")){//通电
                                this.saveAlarm(uartTmp,deviceManage,"2");//存储告警信息
                                deviceManage.setThreeStrandState("1");//通电
                            }
                            if(deviceManage.getDeviceStatus().equals("0")){
                                deviceManage.setDeviceStatus("1");//通电
                            }
                            deviceManageService.updateById(deviceManage);
                        }
                    }else if(uartTmp.getType().equals("4")){//4号子线(type==4)(state==1通电；断电：state==0且电压==200V；缺相：state==0且电压==380V；)
                        //判断是否开启4号子线
                        if(StringUtils.isNotEmpty(deviceManage.getMonitorFourStrand()) && deviceManage.getMonitorFourStrand().equals("0")){
                            //判断告警状态（0-断电/缺相；1-通电；）
                            if(uartTmp.getState().equals("0")){//断电/缺相
                                this.saveAlarm(uartTmp,deviceManage,"0");// //存储告警信息
                                deviceManage.setFourStrandState("0");//断电/缺相
                            }else if(uartTmp.getState().equals("1")){//通电
                                this.saveAlarm(uartTmp,deviceManage,"2");//存储告警信息
                                deviceManage.setFourStrandState("1");//通电
                            }
                            if(deviceManage.getDeviceStatus().equals("0")){
                                deviceManage.setDeviceStatus("1");//通电
                            }
                            deviceManageService.updateById(deviceManage);
                        }
                    }else if(uartTmp.getType().equals("5")){//5-设备通信状态号子线(type==5)(1:通电、0:断线)
                        if(uartTmp.getState().equals("1")){//通电
                            if(!uartTmp.getState().equals(deviceManage.getDeviceStatus())){
                                this.saveAlarm(uartTmp,deviceManage,"4");//存储告警信息
                            }
                        }
                        if(deviceManage.getDeviceStatus().equals("0")){
                            deviceManage.setDeviceStatus("1");//通电
                        }
                        deviceManageService.updateById(deviceManage);
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getInfo(String id) {
        return AjaxResult.success(baseMapper.selectById(id));
    }

    @Override
    public AjaxResult delInfo(String id) {
        baseMapper.updateDel(id);
        return AjaxResult.success();
    }
    @Override
    public AjaxResult delInfos(String[] ids) {
        for(String id:ids){
            baseMapper.updateDel(id);
        }
        return AjaxResult.success();
    }

    /**
     * 根据imei查询设备告警相关信息
     * @param deviceAlarm
     * @return
     */
    @Override
    public List<DeviceAlarm> getAlarmListByImei(DeviceAlarm deviceAlarm){
        return baseMapper.getAlarmListByImei(deviceAlarm);
    }

    /**
     * 检测到离线设备发送短信，修改离线状态
     */
    @Override
    public void updateDeviceAlarm(AlarmTmpVo tmp){
        //查询设备信息
        DeviceManage deviceManage=deviceManageService.getDeviceByImei(tmp.getImei());
        if(ObjectUtil.isNotEmpty(deviceManage)){
            //修改设备状态
            if(!tmp.getDeviceStatus().equals(deviceManage.getDeviceStatus())){
                deviceManage.setDeviceStatus(tmp.getDeviceStatus());
                deviceManageService.updateById(deviceManage);
                if(tmp.getDeviceStatus().equals("0")){//离线发短信
                    sendOfflineSms(deviceManage,"3");
                }
            }
        }
    }
    /**
     * 存储设备告警信息
     * @param uartTmp
     * @param deviceManage
     * @param alarmType
     */
    public void saveAlarm(UartTmp uartTmp,DeviceManage deviceManage,String alarmType){
        DeviceAlarm deviceAlarm=new DeviceAlarm();
        deviceAlarm.setAlarmType(alarmType);
        deviceAlarm.setAlarmLine(uartTmp.getType());
        if(uartTmp.getType().equals("0")){
            deviceAlarm.setLine("主线");
        }else if(uartTmp.getType().equals("1")){
            deviceAlarm.setLine("1号子线");
        }else if(uartTmp.getType().equals("2")){
            deviceAlarm.setLine("2号子线");
        }else if(uartTmp.getType().equals("3")){
            deviceAlarm.setLine("3号子线");
        }else if(uartTmp.getType().equals("4")){
            deviceAlarm.setLine("4号子线");
        }
        deviceAlarm.setImei(uartTmp.getImei());
        deviceAlarm.setBz(uartTmp.getBz());
        deviceAlarm.setAlarmTime(uartTmp.getDatetime());
        deviceAlarm.setCreateBy(DateUtil.now());
        deviceAlarm.setDeviceCode(deviceManage.getDeviceCode());
        deviceAlarm.setGroupId(deviceManage.getGroupId());
        deviceAlarm.setRoadSectionId(deviceManage.getRoadSectionId());
        deviceAlarm.setRoadSection(deviceManage.getRoadSection());
        deviceAlarm.setSiteId(deviceManage.getSiteId());
        deviceAlarm.setSite(deviceManage.getSite());
        deviceAlarm.setLocationId(deviceManage.getLocationId());
        deviceAlarm.setLocation(deviceManage.getLocation());
        deviceAlarm.setDelFlag("0");
        deviceAlarm.setCreateTime(DateTime.now());
        baseMapper.insert(deviceAlarm);
        //发送短信-告警类型（0-断电；1-缺相；2:断电/缺相恢复告警;3-设备断线；4-设备通电)
        if(!deviceAlarm.getAlarmType().equals(4)){
            this.sendSms(deviceAlarm,deviceAlarm.getAlarmType());
        }
        //拨打语音电话-告警类型（0-断电；1-缺相；2:断电/缺相恢复告警;3-设备断线；4-设备通电)
        if(!deviceAlarm.getAlarmType().equals(3) && !deviceAlarm.getAlarmType().equals(4) ){
            this.sendDyvm(deviceAlarm,deviceAlarm.getAlarmType());
        }
    }

    /**
     *  正常告警发送短信
     *  @param alarm 告警信息
     * @param templateType 模板类型：0-断电告警；1-缺相告警；2-断电/缺相恢复告警；3-设备通信异常告警
     */
    public void sendSms(DeviceAlarm alarm,String templateType) {
        SmsConfig smsConfig = smsConfigService.getInfoByType(templateType);
        if(ObjectUtil.isNotEmpty(smsConfig)){
            DeviceGroup group=deviceGroupService.getById(alarm.getGroupId());
            if(ObjectUtil.isNotEmpty(group)){
                //判断是否开启短信提醒(0-开启；1-未开启)
                if(group.getPhoneMsgAlarm().equals("0")){
                    List<DeviceGroupAlarmPhone> list=deviceGroupAlarmPhoneMapper.getListByGroup(group.getId());
                    if(list!=null && list.size()>0){
                        for(DeviceGroupAlarmPhone alarmPhone:list){
                            smsConfig.setPhoneNumbers(alarmPhone.getPhone());
                            smsConfig.setAddress(alarm.getRoadSection()+alarm.getSite()+alarm.getLocation());
                            smsConfig.setCode(alarm.getDeviceCode());
                            smsConfig.setTime(alarm.getAlarmTime());
                            smsConfig.setLine(alarm.getLine());
                            SmsMessage smsMessage = new SmsMessage();
                            smsMessage.setMsgType(templateType);
                            smsMessage.setPhoneNum(alarmPhone.getPhone());
                            smsMessage.setSendTime(DateTime.now());
                            smsMessage.setAddress(alarm.getRoadSection()+alarm.getSite()+alarm.getLocation());
                            smsMessage.setCode(alarm.getDeviceCode());
                            smsMessage.setTime(alarm.getAlarmTime());
                            smsMessage.setStatus("0");
                            smsMessage.setLine(alarm.getLine());
                            AjaxResult ajaxResult = AliSmsUtil.sendSms(smsConfig);
                            if (ajaxResult.isSuccess()) {
                                smsMessageService.save(smsMessage);
                            } else {
                                String errorStr = (String) ajaxResult.get("data");
                                smsMessage.setStatus("1");
                                smsMessage.setErrorDesc(errorStr);
                                smsMessageService.save(smsMessage);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *  设备离线告警发送短信
     *  @param deviceManage 告警信息
     * @param templateType 模板类型：0-断电告警；1-缺相告警；2-断电/缺相恢复告警；3-设备通信异常告警
     */
    public void sendOfflineSms(DeviceManage deviceManage,String templateType) {
        SmsConfig smsConfig = smsConfigService.getInfoByType(templateType);
        if(ObjectUtil.isNotEmpty(smsConfig)){
            DeviceGroup group=deviceGroupService.getById(deviceManage.getGroupId());
            if(ObjectUtil.isNotEmpty(group)){
                //判断是否开启短信提醒(0-开启；1-未开启)
                if(group.getPhoneMsgAlarm().equals("0")){
                    List<DeviceGroupAlarmPhone> list=deviceGroupAlarmPhoneMapper.getListByGroup(group.getId());
                    if(list!=null && list.size()>0){
                        for(DeviceGroupAlarmPhone alarmPhone:list){
                            smsConfig.setPhoneNumbers(alarmPhone.getPhone());
                            smsConfig.setAddress(deviceManage.getRoadSection()+deviceManage.getSite()+deviceManage.getLocation());
                            smsConfig.setCode(deviceManage.getDeviceCode());
                            smsConfig.setTime(DateUtil.now());
                            SmsMessage smsMessage = new SmsMessage();
                            smsMessage.setMsgType(templateType);
                            smsMessage.setPhoneNum(alarmPhone.getPhone());
                            smsMessage.setSendTime(DateTime.now());
                            smsMessage.setAddress(deviceManage.getRoadSection()+deviceManage.getSite()+deviceManage.getLocation());
                            smsMessage.setCode(deviceManage.getDeviceCode());
                            smsMessage.setTime(DateUtil.now());
                            smsMessage.setStatus("0");
                            AjaxResult ajaxResult = AliSmsUtil.sendOnlineSms(smsConfig);
                            if (ajaxResult.isSuccess()) {
                                smsMessageService.save(smsMessage);
                            } else {
                                String errorStr = (String) ajaxResult.get("data");
                                smsMessage.setStatus("1");
                                smsMessage.setErrorDesc(errorStr);
                                smsMessageService.save(smsMessage);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *  拨打语音电话
     *  @param alarm 告警信息
     * @param templateType 模板类型：0-断电告警；1-缺相告警；2-断电/缺相恢复告警；3-设备通信异常告警
     */
    public void sendDyvm(DeviceAlarm alarm,String templateType) {
        DyvmConfig dyvmConfig = dyvmConfigService.getInfoByType(templateType);
        if(ObjectUtil.isNotEmpty(dyvmConfig)){
            DeviceGroup group=deviceGroupService.getById(alarm.getGroupId());
            if(ObjectUtil.isNotEmpty(group)){
                //判断是否开启短信提醒(0-开启；1-未开启)
                if(group.getPhoneMsgAlarm().equals("0")){
                    List<DeviceGroupAlarmPhone> list=deviceGroupAlarmPhoneMapper.getListByGroup(group.getId());
                    if(list!=null && list.size()>0){
                        for(DeviceGroupAlarmPhone alarmPhone:list){
                            dyvmConfig.setPhoneNumbers(alarmPhone.getPhone());
                            dyvmConfig.setContent(alarm.getRoadSection()+alarm.getSite()+alarm.getLocation()+alarm.getLine());
                            dyvmConfig.setTime(alarm.getAlarmTime());
                            DyvmMessage dyvmMessage = new DyvmMessage();
                            dyvmMessage.setMsgType(templateType);
                            dyvmMessage.setPhoneNum(alarmPhone.getPhone());
                            dyvmMessage.setCode(alarm.getDeviceCode());
                            dyvmMessage.setSendTime(DateTime.now());
                            dyvmMessage.setContent(alarm.getRoadSection()+alarm.getSite()+alarm.getLocation()+alarm.getLine());
                            dyvmMessage.setTime(alarm.getAlarmTime());
                            dyvmMessage.setStatus("0");
                            AjaxResult ajaxResult = AliDyvmUtil.sendSingleCallToUser(dyvmConfig);
                            if (ajaxResult.isSuccess()) {
                                dyvmMessageService.save(dyvmMessage);
                            } else {
                                String errorStr = (String) ajaxResult.get("data");
                                dyvmMessage.setStatus("1");
                                dyvmMessage.setErrorDesc(errorStr);
                                dyvmMessageService.save(dyvmMessage);
                            }
                        }
                    }
                }
            }
        }
    }


}
